#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, site 
import re, urllib
import datetime, time
import shutil

import sqlite3dbm

from generator import *
from paneo import *

import web
from sqlobject import *
sqlhub.processConnection = connectionForURI('sqlite://'+ARTICLES_DB)

#render
from web.contrib.template import render_mako

render = render_mako(   directories=[PANEO_ROOT+'/_cms/templates/'],
                        input_encoding='utf-8',
                        output_encoding='utf-8',
                        default_filters=["none_to_blank", "unicode"],
                        encoding_errors='replace', 
                        imports = RENDER_IMPORTS )



class View:

    def __init__(self):
        self.cms = 'pages'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self ):
        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        pages = dic.get('pages')
        dic.close()

        if not pages :
            pages = {}

        if scfg.get("PAGEMAKE") == 'HTML':
            pages = GetHtmlMenuPages() 

        return render.pages(    
                                cms = self.cms,                        
                                scfg = scfg, 
                                pages = pages,
                                mode = 'view',
                                id = None,
                                html_file = None,
        )


#PANEO PAGE CONTENTS EDIT
class Edit:

    def __init__(self):
        self.cms = 'pages'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self, id='index' ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        pages = dic.get('pages')
        dic.close()

        p = pages.get(id)
        html_file = p.GetPageTemplateFile(id)
        templates = p.GetPageTemplateNames(id)
        page_img = p.GetPageImageFields('page',id)

        return render.pages(     
                                cms = self.cms,                        
                                scfg = scfg, 
                                pages = pages,
                                mode = 'edit',

                                id = id,
                                html_file = html_file,
                                templates = templates,
                                page_img = page_img
        )


    def POST( self, id=None ):

        i = web.input(  IDX=0,
                        TYPE='MENU',
                        PARENT='',
                        LINK='',
                        FILENAME='index' )

        #値のチェック
        web.ctx.MSG = u""
        reg = re.compile(r'^[0-9A-Za-z]+$')
        r = reg.search(i.FILENAME.encode('utf8')) 
        if r is None:
            web.ctx.MSG = u"ファイル名は半角英数字のみ有効です。"
            return self.GET( id )

        dic = sqlite3dbm.sshelve.open(PANEO_DB)

        scfg = dic.get('siteconfig')
        pages = dic.get('pages')

        p = pages.get(id) 
        if p is None:
            return web.notfound()

        #PAGE削除
        if i.has_key("PAGE_DELETE") :
            if pages.has_key(id):
                del pages[id] 
                if os.path.exists(PANEO_SITE_DATA_DIR+id+'.html'):
                    os.remove(PANEO_SITE_DATA_DIR+id+'.html')
                dic['pages'] = pages
                dic.close()
            return web.seeother("/paneo/pages/")

        #PAGEの更新
        p.IDX = i.IDX
        p.TYPE = i.TYPE
        p.PARENT = i.PARENT
        p.VIEWED = i.VIEWED
        p.TITLE = i.TITLE
        p.LINK = i.LINK
        p.PostPageImageFields('page',i,id) #IMG

        #ID 変更
        if i.FILENAME != id :
            if pages.has_key(i.FILENAME):
                web.ctx.MSG = u"%sはすでに利用されています" % i.FILENAME
                dic.close()
                return self.GET(id)
            else:
                id = i.FILENAME


        #TEMPLATE更新
        p.TEMPLATE_SYSTEM_USE = i.has_key("TEMPLATE_SYSTEM_USE")
        if p.TEMPLATE != i.TEMPLATE:
            p.PostPageChangeTemplateFile(id,i.TEMPLATE)
        else:
            if i.has_key("HTMLTEMPLATE"):
                p.PostPageTemplateFile(id,i.HTMLTEMPLATE)
        p.TEMPLATE = i.TEMPLATE

        pages[id] = p

        dic['pages'] = pages
        dic.close()

        return self.GET( id )


class New:

    def __init__(self):
        self.cms = 'pages'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        pages = dic.get('pages')
        dic.close()

        max_id = 0 
        for k,v in pages.items():
            if k.find('page') != -1:
                i = int(k.replace('page',''))
                if i > max_id :
                    max_id = i
        max_id = max_id + 1
        id = 'page%s' % max_id

        p = PaneoPage()
        p.IDX = len( pages ) 
        p.TYPE = 'MENU'
        p.TEMPLATE = 'skelton'
        p.TEMPLATE_SYSTEM_USE = False
        p.PARENT = ''
        p.VIEWED = 1
        p.TITLE =  u'新しいページ%s' % max_id
        p.LINK = ''
        p.IMG = {}

        templates = p.GetPageTemplateNames(id)

        pages[id] = p

        return render.pages(  
                                cms = self.cms,                        
                                scfg = scfg, 
                                pages = pages,
                                mode = 'new',

                                id = id,
                                html_file = None,
                                templates = templates,
        )


    def POST( self ):

        i = web.input()

        #値のチェック
        web.ctx.MSG = u""
        if i.FILENAME == 'index':
            web.ctx.MSG = u"新規登録でindexは指定できません。"
            return self.GET()

        reg = re.compile(r'^[0-9A-Za-z]+$')
        r = reg.search(i.FILENAME.encode('utf8')) 
        if r is None:
            web.ctx.MSG = u"ファイル名は半角英数字のみ有効です。"
            return self.GET()

        dic = sqlite3dbm.sshelve.open(PANEO_DB)

        scfg = dic.get('siteconfig')
        pages = dic.get('pages')

        if pages.has_key(i.FILENAME):
            web.ctx.MSG = u"%sはすでに利用されています" % i.FILENAME
            dic.close()
            return self.GET()

        #PAGE追加
        id=i.FILENAME

        p = PaneoPage()
        p.IDX = i.IDX
        p.TYPE = i.TYPE
        p.PARENT = i.PARENT
        p.TEMPLATE = i.TEMPLATE
        p.VIEWED = i.VIEWED
        p.TITLE = i.TITLE
        p.LINK = i.LINK

        pages[id] = p
        dic['pages'] = pages
        dic.close()

        ##TEMPLATEのバックアップ
        #if os.path.exists(PANEO_SITE_DATA_DIR+id+'.html'):
        #    shutil.copyfile(PANEO_SITE_DATA_DIR+id+'.html',PANEO_SITE_DATA_DIR+'backup/'+id+'.html.'+dt+'.bak')
        ##TEMPLATEのコピー
        #shutil.copyfile(PANEO_CMS_PAGE_TEMPLATES_DIR+i.TEMPLATE+'.html', PANEO_SITE_DATA_DIR+id+'.html')

        return web.seeother('http://' + web.ctx.host + '/paneo/pages/edit/%s/' % id)




